<template>
  <div>
    <t-form :rules="FORM_RULES" :data="formData" @submit="smsLogin">
      <t-form-item label="手机号" name="phone">
        <t-input v-model="formData.phone" placeholder="请输入手机号" />
      </t-form-item>
      <t-form-item label="短信验证码" name="smsCode">
        <t-input v-model="formData.smsCode" placeholder="请输入验证码" /> <t-button theme="default"
          :disabled="sendSafeCodeStatus" @click="sendSms">{{desc}}发送验证码</t-button>
      </t-form-item>
      <t-form-item>
        <t-button type="submit">登录</t-button>
      </t-form-item>
    </t-form>
    <p class="description">
      温馨提示：通过手机验证后,未注册用户自动注册为会员
    </p>
  </div>
</template>

<script setup>
  import {
    ref
  } from 'vue'
  import $eventBus from '@/utils/eventBus'
  import {
    useUserStore
  } from '@/store'
  import {
    sendLoginSms,
    phoneLogin
  } from '@/api/user'
  import {
    MessagePlugin
  } from 'tdesign-vue-next';

  const userStore = useUserStore()
  const formData = ref({
    phone: '',
    safeCode: '',
    smsCode: ''
  })
  const FORM_RULES = {
    phone: [{
      required: true,
      message: '手机号必填'
    }],
    smsCode: [{
      required: true,
      message: '短信验证码必填'
    }],
  };

  const sendSafeCodeStatus = ref(false)
  const timer = ref(null)
  const count = ref(0)
  const TIME_COUNT = 10
  const desc = ref('')
  //发送验证码
  const sendSms = () => {
    if (formData.value.phone.length !== 11) {
      MessagePlugin.error('请输入正确的手机号')
      return;
    }
    sendSafeCodeStatus.value = true
    localStorage.setItem('sendSafeCodeStatus', true)

    desc.value = count.value + 's后'
    if (!timer.value) {
      count.value = TIME_COUNT
      timer.value = setInterval(() => {

        if (count.value > 0 && count.value <= TIME_COUNT) {
          count.value--
        } else {
          clearInterval(timer.value)
          timer.value = null
          desc.value = ''

        }
      }, 1000)
    }

    sendLoginSms({
        phone: formData.value.phone
      })
      .then(ret => {
        MessagePlugin.info('验证码己发送至手机')
      })
      .catch(e => {
        MessagePlugin.error(e.msg)
      })
      .finally(() => {
        localStorage.setItem('sendSafeCodeStatus', false)
        sendSafeCodeStatus.value = false
      })
  }
  //短信登录
  const smsLogin = () => {
    phoneLogin({
      phone: formData.value.phone,
      code: formData.value.smsCode
    }).then(ret => {
      console.log('ret ', JSON.stringify(ret))
      if (ret.access_token) {
        $eventBus.emit('LoginSuccessEvent');
        MessagePlugin.success('登录成功');
        let token = ret.access_token;
        userStore.saveToken(token);
      }
    }).
    catch(e => {
      console.log(JSON.stringify(e))
      MessagePlugin.error(e.msg)
    })
  }
  let status = localStorage.getItem('sendSafeCodeStatus')
  if (status) {
    sendSafeCodeStatus.value = status
  }
</script>

<style scoped>
  .description {
    margin-top: 15px;
    font-size: 13px;
    color: #bdbdbd;
  }
</style>
